﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using KeRui.Common;
using KeRui.Upload;
using System.IO;

public partial class Manage_Seller_SellerAdItem : System.Web.UI.Page
{
    protected KeRui.BLL.SellerAD bllSellerAd;
    protected KeRui.Model.SellerAD modelSellerAD = new KeRui.Model.SellerAD();
    public string Act = ManageHelper.PageAct();
    private ManageErrMsg nsb = new ManageErrMsg();
    protected string ActFlag = "addsave";
    protected string ActName = "添加";
    protected int state = -1;
    protected KeRui.BLL.Ad bllAD = new KeRui.BLL.Ad();//广告位选择
    protected KeRui.Model.Ad modelAd = new KeRui.Model.Ad();
    protected KeRui.BLL.Seller bllSeller = new KeRui.BLL.Seller();//商户选择
    protected int intNum = 0;
    protected int SiteID = -1;
    protected int AdID = -1;

    protected void Page_Load(object sender, EventArgs e)
    {
        ManageHelper.CheckAdminLogin();//登陆判断
        SiteID = PageRequest.GetInt("SiteID", -1);
        state = PageRequest.GetInt("state", -1);
        AdID = PageRequest.GetInt("AdID", -1);
        bllSellerAd = new KeRui.BLL.SellerAD();
        modelAd = bllAD.GetModel(AdID);
        switch (Act)
        {
            case "addsave":
                SellerAdAdd();
                break;
            case "edit":
                Edit();
                break;
            case "editsave":
                EditSave();
                break;
            case "del":
                Del();
                break;
            case "state":
                State();
                break;
            case "adbuynumandunit":
                GetAdInfo();
                break;
            default:
                break;
        }
    }

    #region 添加
    private void SellerAdAdd()
    {
        ManageHelper.CheckAdminPower("site_selleradAdd_" + SiteID);//权限
        modelSellerAD.AdName = PageRequest.GetString("AdName");
        if (modelSellerAD.AdName == "")
        {
            nsb.AddErr("请填写广告名称。");
            nsb.ChkErr();
        }
        modelSellerAD.SellerID = PageRequest.GetInt("SellerID", -1);
        if (modelSellerAD.SellerID == -1)
        {
            nsb.AddErr("请选择商户。");
        }
        modelSellerAD.AdID = PageRequest.GetInt("AdID", -1);
        if (modelSellerAD.AdID == -1)
        {
            nsb.AddErr("请选择广告位。");
            nsb.ChkErr();
        }
        try
        {
            modelSellerAD.StartDate = DateTime.Parse(PageRequest.GetString("StartDate"));
        }
        catch
        {
            nsb.AddErr("日期格式不正确。");
        }
        int CountNum = PageRequest.GetInt("CountNum", -1);
        if (CountNum < 1)
        {
            nsb.AddErr("请输入正确的购买量");
        }

        KeRui.Model.Ad ModelAdInfo = new KeRui.Model.Ad();
        ModelAdInfo = bllAD.GetModel(modelSellerAD.AdID);
        int totalNum = (ModelAdInfo.BuyNum) * CountNum;
        string BuyUnit = GetStrUnit(ModelAdInfo.BuyUnit);
        switch (ModelAdInfo.BuyUnit)
        {
            case 1:
                modelSellerAD.EndDate = modelSellerAD.StartDate.AddDays(totalNum);
                break;
            case 2:
                modelSellerAD.EndDate = modelSellerAD.StartDate.AddDays(totalNum * 7);
                break;
            case 3:
                modelSellerAD.EndDate = modelSellerAD.StartDate.AddMonths(totalNum);
                break;
            case 4:
                modelSellerAD.EndDate = modelSellerAD.StartDate.AddMonths(totalNum * 3);
                break;
            case 5:
                modelSellerAD.EndDate = modelSellerAD.StartDate.AddYears(totalNum);
                break;
            default:
                break;
        }

        if (bllSellerAd.CheckTime(AdID, modelSellerAD.StartDate, modelSellerAD.EndDate, modelSellerAD.ID) > 0)
        {
            nsb.AddErr("输入日期与以前的日期交叉，您可以选择删除时间交叉的广告或修改到别的时间。"); nsb.ChkErr();
        }

        Upload upload = new Upload();
        UploadedFile upfile = upload.Files[0];
        modelSellerAD.AdText = upfile.FileName;
        switch (ModelAdInfo.AdType)
        {
            case 1:
                modelSellerAD.AdText = PageRequest.GetString("AdText");
                if (modelSellerAD.AdText == "")
                {
                    nsb.AddErr("请填写广告信息。");
                }
                break;
            case 2:
                if (modelSellerAD.AdText == "")
                {
                    nsb.AddErr("请选择一个图片。");
                }
                else
                {
                    if (!ChkExt(upfile.Extension, 0))
                    {
                        nsb.AddErr("文件格式不正确。请选择一个图片");
                    }
                }
                break;
            case 3:
                if (modelSellerAD.AdText == "")
                {
                    nsb.AddErr("请选择一个Flash。");
                }
                else
                {
                    if (!ChkExt(upfile.Extension, 1))
                    {
                        nsb.AddErr("文件格式不正确。请选择一个Flash。");
                    }
                }
                break;
            default: break;
        }
        nsb.ChkErr();
        modelSellerAD.AdUrl = PageRequest.GetString("AdUrl");
        if (modelSellerAD.AdUrl == "")
        {
            nsb.AddErr("请填写广告URL。");
        }
        if (modelSellerAD.StartDate > DateTime.Now)
        {
            modelSellerAD.State = 0;
        }
        else if (modelSellerAD.EndDate < DateTime.Now)
        {
            modelSellerAD.State = 2;
        }
        else if (modelSellerAD.StartDate > DateTime.Now || DateTime.Now < modelSellerAD.EndDate)
        {
            modelSellerAD.State = 1;
        }
        else
        {
            nsb.AddErr("ERROR：状态计算有误。");
        }
        modelSellerAD.CreateIP = Utils.GetRealIP();


        #region 上传广告

        if (ModelAdInfo.AdType > 1)
        {
            string fileExt = modelSellerAD.AdText;
            string Path = CreatePathWithDate("/Upload/SellerAD/", "YY-MM:DD");
            modelSellerAD.AdText = Path + System.Guid.NewGuid() + GetExt(upfile.Extension);
            upfile.SaveAs(Server.MapPath(modelSellerAD.AdText)); //保存
        }
        #endregion
        nsb.ChkErr();
        int RetFlag = bllSellerAd.Add(modelSellerAD);

        ManageHelper.AddLog("site_selleradAdd", "添加了“" + modelSellerAD.AdName + "”商户广告。");

        KeRui.TemplateMaker.Publish publish = new KeRui.TemplateMaker.Publish();

        string publishInfo = publish.PublishAd(modelSellerAD.AdID, 1);

        if (publishInfo != "")
        {
            nsb.AddErr("数据已经添加到数据库。ERROR：" + publishInfo); nsb.ChkErr();
        }

        Response.Redirect("SellerAdList.aspx?adid=" + modelAd.AdID + "&siteid=" + modelAd.SiteID + "&sucmsg=添加成功。");

        //Response.Write("<script>window.parent.location.href=\"SellerAdList.aspx?sucmsg=添加成功。\";</script>");
    }
    #endregion

    #region 反显修改页面
    private void Edit()
    {
        ActFlag = "editsave";
        ActName = "修改";
        int ID = PageRequest.GetInt("ID", -1);
        if (ID == -1)
        {
            nsb.AddErr("Error:信息不存在。");
            nsb.ChkErr();
        }
        modelSellerAD = bllSellerAd.GetModel(ID);

        if (modelAd == null)
        {
            nsb.AddErr("没有找到广告位。"); nsb.ChkErr();
        }
        DateTime stardate = modelSellerAD.StartDate;
        DateTime enddate = modelSellerAD.EndDate;
        TimeSpan ts = enddate - stardate;
        switch (modelAd.BuyUnit)
        {
            case 1://1天
                intNum = ts.Days;
                break;
            case 2://2周 
                intNum = (ts.Days / 7);
                break;
            case 3://3月
                intNum = (enddate.Year - stardate.Year) + (enddate.Month - stardate.Month);
                break;
            case 4://4季
                intNum = ((enddate.Year - stardate.Year) + (enddate.Month - stardate.Month)) / 3;
                break;
            case 5://5年
                intNum = (enddate.Year - stardate.Year);
                break;
            default:
                break;
        }
        intNum = intNum / modelAd.BuyNum;
    }
    #endregion

    #region 修改时保存
    private void EditSave()
    {
        ManageHelper.CheckAdminPower("site_selleradedit_" + SiteID);//权限
        modelSellerAD.ID = PageRequest.GetInt("ID", -1);
        KeRui.Model.SellerAD old_sellerAdModel = bllSellerAd.GetModel(modelSellerAD.ID);
        modelSellerAD.AdName = PageRequest.GetString("AdName");
        if (modelSellerAD.AdName == "")
        {
            nsb.AddErr("请填写广告名称。");
            nsb.ChkErr();
        }
        modelSellerAD.SellerID = PageRequest.GetInt("SellerID", -1);
        if (modelSellerAD.SellerID == -1)
        {
            nsb.AddErr("请选择商户。");
        }
        modelSellerAD.AdID = PageRequest.GetInt("AdID", -1);
        if (modelSellerAD.AdID == -1)
        {
            nsb.AddErr("请选择广告位。");
            nsb.ChkErr();
        }
        try
        {
            modelSellerAD.StartDate = DateTime.Parse(PageRequest.GetString("StartDate"));
        }
        catch
        {
            nsb.AddErr("日期格式不正确。");
        }
        int CountNum = PageRequest.GetInt("CountNum", -1);
        if (CountNum < 1)
        {
            nsb.AddErr("请输入正确的购买量");
        }
        #region 上传XX判断
        KeRui.Model.Ad ModelAdInfo = new KeRui.Model.Ad();
        ModelAdInfo = bllAD.GetModel(modelSellerAD.AdID);
        int totalNum = (ModelAdInfo.BuyNum) * CountNum;
        string BuyUnit = GetStrUnit(ModelAdInfo.BuyUnit);
        switch (ModelAdInfo.BuyUnit)
        {
            case 1:
                modelSellerAD.EndDate = modelSellerAD.StartDate.AddDays(totalNum);
                break;
            case 2:
                modelSellerAD.EndDate = modelSellerAD.StartDate.AddDays(totalNum * 7);
                break;
            case 3:
                modelSellerAD.EndDate = modelSellerAD.StartDate.AddMonths(totalNum);
                break;
            case 4:
                modelSellerAD.EndDate = modelSellerAD.StartDate.AddMonths(totalNum * 3);
                break;
            case 5:
                modelSellerAD.EndDate = modelSellerAD.StartDate.AddYears(totalNum);
                break;
            default:
                break;
        }

        if (bllSellerAd.CheckTime(AdID, modelSellerAD.StartDate, modelSellerAD.EndDate, modelSellerAD.ID) > 0)
        {
            nsb.AddErr("输入日期与以前的日期交叉，您可以选择删除时间交叉的广告或修改到别的时间。"); nsb.ChkErr();
        }

        Upload upload = new Upload();
        UploadedFile upfile = upload.Files[0];
        modelSellerAD.AdText = upfile.FileName;
        switch (ModelAdInfo.AdType)
        {
            case 1:
                modelSellerAD.AdText = PageRequest.GetString("AdText");
                if (modelSellerAD.AdText == "")
                {
                    nsb.AddErr("请填写广告信息。");
                }
                break;
            case 2:
                if (modelSellerAD.AdText == "")
                {
                }
                else
                {
                    if (!ChkExt(upfile.Extension, 0))
                    {
                        nsb.AddErr("文件格式不正确。请选择一个图片");
                    }
                }
                break;
            case 3:
                if (modelSellerAD.AdText == "")
                {
                }
                else
                {
                    if (!ChkExt(upfile.Extension, 1))
                    {
                        nsb.AddErr("文件格式不正确。请选择一个Flash。");
                    }
                }
                break;
            default: break;
        }
        nsb.ChkErr();
        #endregion
        modelSellerAD.AdUrl = PageRequest.GetString("AdUrl");
        if (modelSellerAD.AdUrl == "")
        {
            nsb.AddErr("请填写广告URL。");
        }
        modelSellerAD.CreateIP = Utils.GetRealIP();
        #region 上传广告
        if (modelSellerAD.AdText == "")
        {
            modelSellerAD.AdText = old_sellerAdModel.AdText;
        }
        else
        {
            if (ModelAdInfo.AdType > 1)
            {
                string fileExt = modelSellerAD.AdText;
                string Path = CreatePathWithDate("/Upload/SellerAD/", "YY-MM:DD");
                modelSellerAD.AdText = Path + System.Guid.NewGuid() + GetExt(upfile.Extension);
                upfile.SaveAs(Server.MapPath(modelSellerAD.AdText)); //保存
            }
            #region 修改时候先把以前的广告删除
            if (old_sellerAdModel == null)
            {
                nsb.AddErr("要修改的文件不存在。。"); nsb.ChkErr();
            }
            try
            {
                old_sellerAdModel.AdText = Server.MapPath(old_sellerAdModel.AdText);
                if (File.Exists(old_sellerAdModel.AdText))
                {
                    File.Delete(old_sellerAdModel.AdText);
                }
            }
            catch
            { }
            #endregion
        }
        #endregion
        nsb.ChkErr();
        int RetFlag = bllSellerAd.Update(modelSellerAD);
        ManageHelper.AddLog("system_selleradedit", "修改了“" + modelSellerAD.AdName + "”商户广告。");

        KeRui.TemplateMaker.Publish publish = new KeRui.TemplateMaker.Publish();

        string publishInfo = publish.PublishAd(modelSellerAD.AdID, 1);

        if (publishInfo != "")
        {
            nsb.AddErr("数据已经添加到数据库。ERROR：" + publishInfo); nsb.ChkErr();
        }

        Response.Redirect("SellerAdList.aspx?adid=" + modelAd.AdID + "&siteid=" + modelAd.SiteID + "&sucmsg=修改成功！");
        //Response.Write("<script>window.parent.location.href=\"Adlist.aspx?sucmsg=   。\";</script>");
    }
    #endregion

    #region 删除
    private void Del()
    {
        ManageHelper.CheckAdminPower("site_selleraddel_" + SiteID);//权限
        int ID = PageRequest.GetInt("ID", -1);
        if (ID == -1)
        {
            nsb.AddErr("该站点不存在。");
            nsb.ChkErr();
        }
        modelSellerAD = bllSellerAd.GetModel(ID);
        if (File.Exists(Server.MapPath(modelSellerAD.AdText)))
        {
            File.Delete(Server.MapPath(modelSellerAD.AdText));
        }
        bllSellerAd.Delete(ID);

        KeRui.TemplateMaker.Publish publish = new KeRui.TemplateMaker.Publish();
        publish.PublishAd(modelSellerAD.AdID, 1);

        ManageHelper.AddLog("system_selleraddel", "删除了“" + modelSellerAD.AdName + "”商户广告。");
        Response.Redirect("SellerAdList.aspx?adid=" + modelAd.AdID + "&siteID=" + modelAd.SiteID + "&state=" + state + "&sucmsg=恭喜。删除成功。");
    }
    #endregion

    #region 解锁和锁定
    private void State()
    {
        int UserID = PageRequest.GetInt("ID", -1);
        int st = PageRequest.GetInt("st", 0);
        if (UserID == -1)
        {
            nsb.AddErr("对不起。你想要操作的用户不存在。");
            nsb.ChkErr();
        }
        KeRui.BLL.Member bllMember = new KeRui.BLL.Member();
        int RetInt = bllMember.ChageState(UserID, 2);
        if (st == 1)
        {
            Response.Redirect("List.aspx?sucmsg=恭喜。锁定成功。");
        }
        else
        {
            Response.Redirect("List.aspx?sucmsg=恭喜。解锁成功。");
        }
    }
    #endregion

    #region 获取购买单位
    private void GetAdInfo()
    {
        Response.Write(modelAd.AdType + "|<font style='color:red'>*</font>" + modelAd.BuyNum + GetStrUnit(modelAd.BuyUnit));
        Response.End();

    }

    protected string GetStrUnit(int intUnit)
    {
        string StrUnit = "";//1天 2周 3月 4季 5年
        switch (intUnit)
        {
            case 1:
                StrUnit = "天";
                break;
            case 2:
                StrUnit = "周";
                break;
            case 3:
                StrUnit = "月";
                break;
            case 4:
                StrUnit = "季";
                break;
            case 5:
                StrUnit = "年";
                break;
            default: break;

        }
        return StrUnit;
    }
    #endregion

    #region 根据日期创建文件夹
    public string CreatePathWithDate(string strV, string strT)
    {
        string uploadpath = "", s = "";

        //替换strT里的年月日伪字符
        if (strT.IndexOf(":") >= 0)
        {
            string[] strTs = strT.Split(":".ToCharArray());
            for (int i = 0; i < strTs.Length; i++)
            {
                strTs[i] = strTs[i].Replace("YY", DateTime.Now.Year.ToString());
                strTs[i] = strTs[i].Replace("MM", DateTime.Now.Month.ToString());
                strTs[i] = strTs[i].Replace("DD", DateTime.Now.Day.ToString());
                if (i != strTs.Length)
                {
                    uploadpath = uploadpath + strTs[i] + "/";
                }
                else
                {
                    uploadpath = uploadpath + strTs[i];
                }
                DirectoryInfo Fsofolder = new DirectoryInfo(Server.MapPath(strV + uploadpath));
                if (!Fsofolder.Exists)
                {
                    Fsofolder.Create();
                }
            }
            s = strV + uploadpath;
        }
        else
        {
            uploadpath = strT.Replace("YY", DateTime.Now.Year.ToString());
            uploadpath = uploadpath.Replace("MM", DateTime.Now.Month.ToString());
            uploadpath = uploadpath.Replace("DD", DateTime.Now.Day.ToString());
            DirectoryInfo Fsofolder = new DirectoryInfo(Server.MapPath(strV + uploadpath));
            if (!Fsofolder.Exists)
            {
                Fsofolder.Create();
                s = strV + uploadpath + "/";
            }
        }
        return s;
    }
    private string GetExt(string filePath)
    {
        return filePath.Substring(filePath.LastIndexOf("."));
    }
    /// <summary>
    /// 判断后缀名
    /// </summary>
    /// <param name="filePath">文件路径</param>
    /// <param name="type">0.图片 1.Flash</param>
    /// <returns>True Or Flase</returns>
    private bool ChkExt(string filePath, int type)
    {
        bool flag = false;
        string ext = GetExt(filePath);
        string Exts = "";
        if (type == 0)//图片
        {
            Exts = ".jpg.gif.jpeg.jpe.png.bmp";
        }
        else if (type == 1)
        {
            Exts = ".swf";
        }
        if (Exts.IndexOf(ext.ToLower()) != -1)
        {
            flag = true;
        }
        return flag;
    }
    #endregion
}
